<template>
  <div class="health-consultation">
    <div class="container py-4">
      <h1 class="text-center mb-4">健康咨询</h1>
      
      <div class="row">
        <div class="col-lg-8 mx-auto">
          <div class="card shadow">
            <div class="card-body">
              <div class="chat-container">
                <div class="chat-messages" ref="chatMessages">
                  <div v-for="(message, index) in messages" :key="index" 
                       :class="['message', message.type === 'user' ? 'user-message' : 'system-message', message.isTyping ? 'typing-message' : '']">
                    <div class="message-content">
                      {{ message.text }}
                      <span v-if="message.isTyping" class="typing-cursor"></span>
                    </div>
                    <div class="message-time">
                      {{ formatTime(message.timestamp) }}
                    </div>
                  </div>
                  
                  <!-- 添加加载指示器 -->
                  <div v-if="isLoading" class="message system-message loading-message">
                    <div class="message-content">
                      <div class="loading-dots">
                        <span></span>
                        <span></span>
                        <span></span>
                      </div>
                    </div>
                  </div>
                </div>
                
                <div class="chat-input-wrapper">
                  <div class="input-group custom-input-group">
                    <div class="input-icon">
                      <i class="bi bi-heart-pulse"></i>
                    </div>
                    <input 
                      type="text" 
                      class="form-control custom-input" 
                      placeholder="请输入您的健康问题..." 
                      v-model="userInput"
                      @keyup.enter="validateAndSend"
                      :class="{'is-invalid': showInputError}"
                    >
                    <button 
                      class="btn btn-send" 
                      @click="validateAndSend"
                      :disabled="isLoading"
                    >
                      <i class="bi" :class="[isLoading ? 'bi-hourglass-split' : 'bi-send-fill']"></i>
                      <span>{{ isLoading ? '天机推衍...' : '健康解析' }}</span>
                    </button>
                  </div>
                  <div class="invalid-feedback" v-if="showInputError">
                    请输入您想咨询的问题
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <div class="card mt-4">
            <div class="card-header bg-light">
              <h5 class="mb-0">健康咨询常见问题</h5>
            </div>
            <div class="card-body">
              <div class="quick-questions">
                <button 
                  v-for="(question, index) in suggestedQuestions" 
                  :key="index"
                  class="btn btn-outline-secondary me-2 mb-2"
                  @click="askSuggestedQuestion(question)"
                >
                  {{ question }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Health',
  data() {
    return {
      userInput: '',
      messages: [
        {
          type: 'system',
          text: '您好，欢迎来到健康咨询。我可以帮您分析体质、健康规划和保健建议，请问有什么想咨询的？',
          timestamp: new Date()
        }
      ],
      suggestedQuestions: [
        '我的体质如何？',
        '今年我的健康运势如何？',
        '我需要注意哪些健康问题？',
        '如何根据命理改善健康？'
      ],
      responseMap: {
        '我的体质如何？': '根据您的八字分析，您属于偏阴虚体质，容易感到疲劳和手脚冰凉。建议增加适当运动，注意保暖，饮食上可多吃温性食物如姜、红枣等。',
        '今年我的健康运势如何？': '您今年的健康运势稳定，但春季和秋季交替时需要特别注意呼吸系统的保养。建议适当增加户外活动，加强免疫力。',
        '我需要注意哪些健康问题？': '从命理上看，您需要特别关注消化系统和肝脏健康，建议定期体检，保持良好作息，避免熬夜和过度劳累，饮食宜清淡。',
        '如何根据命理改善健康？': '基于您的五行分析，您缺乏金元素，可以通过在饮食中增加白色食物（如白萝卜、梨等），同时佩戴金属饰品来平衡五行，提升健康状态。'
      },
      showInputError: false,
      isLoading: false
    }
  },
  methods: {
    validateAndSend() {
      if (!this.userInput.trim()) {
        this.showInputError = true;
        setTimeout(() => {
          this.showInputError = false;
        }, 3000);
        return;
      }
      
      this.showInputError = false;
      this.sendMessage();
    },
    sendMessage() {
      if (this.isLoading) return;
      
      // 添加用户消息
      this.messages.push({
        type: 'user',
        text: this.userInput,
        timestamp: new Date()
      });
      
      const userQuestion = this.userInput;
      this.userInput = '';
      
      this.isLoading = true;
      
      // 模拟处理延迟
      setTimeout(() => {
        // 查找预设回答或给出默认回答
        let response = '';
        
        if (this.responseMap[userQuestion]) {
          response = this.responseMap[userQuestion];
        } else {
          // 简单的关键词匹配
          if (userQuestion.includes('健康') || userQuestion.includes('体质')) {
            response = '从您的命盘来看，您的体质偏向阳虚，容易感到疲倦和精神不振。建议增加适当运动，保证充足睡眠，饮食方面可适当增加温性食物。';
          } else if (userQuestion.includes('疾病') || userQuestion.includes('生病')) {
            response = '您的八字显示肝胆经络较弱，需要注意肝胆系统的保养。日常可以多喝水，避免熬夜，适量摄入绿色蔬菜，对肝脏有益。';
          } else if (userQuestion.includes('饮食') || userQuestion.includes('食疗')) {
            response = '根据您的命理，您适合清淡而富有营养的饮食结构。特别推荐黑色食物（如黑豆、黑芝麻等）来补肾，黄色食物（如南瓜、玉米等）来调理脾胃。';
          } else {
            response = '根据八字分析，您需要重视心肺功能的保养。建议您保持规律作息，避免过度劳累，适当进行有氧运动如慢跑、瑜伽等，有助于提升整体健康水平。';
          }
        }
        
        // 隐藏加载指示器
        this.isLoading = false;
        
        // 创建系统回复但文本为空
        const newMessage = {
          type: 'system',
          text: '',
          timestamp: new Date(),
          isTyping: true // 标记为正在打字中
        };
        
        // 添加空消息到聊天记录
        this.messages.push(newMessage);
        
        // 打字机效果
        let index = 0;
        const typingInterval = setInterval(() => {
          // 每次增加一个字符
          newMessage.text += response.charAt(index);
          index++;
          
          // 每次添加字符后立即滚动到底部
          this.scrollToBottom();
          
          // 当完成打字效果后
          if (index >= response.length) {
            clearInterval(typingInterval);
            
            // 打字效果完成后标记打字完成
            newMessage.isTyping = false;
            
            // 确保完全滚动到底部
            setTimeout(() => {
              this.scrollToBottom();
            }, 100);
          }
        }, 30); // 控制打字速度
      }, 1000);
    },
    askSuggestedQuestion(question) {
      this.userInput = question;
      this.validateAndSend();
    },
    formatTime(timestamp) {
      return new Date(timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    },
    scrollToBottom() {
      this.$nextTick(() => {
        if (this.$refs.chatMessages) {
          this.$refs.chatMessages.scrollTop = this.$refs.chatMessages.scrollHeight;
        }
      });
    }
  },
  mounted() {
    this.scrollToBottom();
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 500px;
  background: url('');
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
  max-height: 400px;
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 12px;
  margin-bottom: 1rem;
  box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.05);
}

.message {
  max-width: 80%;
  padding: 12px 18px;
  border-radius: 18px;
  position: relative;
  margin-bottom: 8px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s ease;
}

.message:hover {
  transform: translateY(-2px);
}

.user-message {
  align-self: flex-end;
  background: linear-gradient(135deg, #3cba92 0%, #1d8c6b 100%);
  color: white;
  border-bottom-right-radius: 4px;
}

.system-message {
  align-self: flex-start;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8edf2 100%);
  color: #333;
  border-bottom-left-radius: 4px;
}

.message-time {
  font-size: 0.7rem;
  text-align: right;
  margin-top: 4px;
  opacity: 0.7;
}

.chat-input-wrapper {
  padding: 1rem;
  border-top: 1px solid #e9ecef;
  background-color: #f8f9fa;
  border-radius: 0 0 12px 12px;
  position: relative;
}

.custom-input-group {
  display: flex;
  align-items: center;
  border-radius: 30px;
  overflow: hidden;
  background-color: white;
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
  border: 1px solid #e0e0e0;
  padding: 5px;
}

.input-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 15px;
  color: #6c757d;
}

.custom-input {
  border: none;
  padding: 12px 15px;
  flex: 1;
  background: transparent;
  border-radius: 0;
}

.custom-input:focus {
  box-shadow: none;
  outline: none;
}

.btn-send {
  border-radius: 24px;
  padding: 10px 25px;
  background: linear-gradient(135deg, #3cba92 0%, #1d8c6b 100%);
  color: white;
  border: none;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
}

.btn-send:hover {
  background: linear-gradient(135deg, #1d8c6b 0%, #136553 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.btn-send:disabled {
  background: #cccccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.quick-questions {
  display: flex;
  flex-wrap: wrap;
  gap: 0.8rem;
}

.card {
  border: none;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  border-radius: 12px;
}

.card .card-header {
  background: linear-gradient(135deg, #f8f9fa 0%, #eaecef 100%);
  border-bottom: none;
  border-radius: 12px 12px 0 0;
}

.btn-outline-secondary {
  border-radius: 30px;
  padding: 8px 16px;
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  color: #475569;
  border: 1px solid #cbd5e1;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-outline-secondary:hover {
  background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
  color: #334155;
  transform: translateY(-2px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.invalid-feedback {
  display: block;
  color: #dc3545;
  margin-top: 0.5rem;
  padding-left: 1rem;
}

/* 添加响应式调整 */
@media (max-width: 576px) {
  .btn-send span {
    display: none;
  }
  
  .btn-send {
    padding: 10px 15px;
  }
  
  .message {
    max-width: 90%;
  }
}

/* 添加加载指示器样式 */
.loading-message {
  align-self: flex-start;
  background: linear-gradient(135deg, #f5f7fa 0%, #e8edf2 100%);
  padding: 15px 20px;
  min-width: 80px;
}

.loading-dots {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.loading-dots span {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #6c757d;
  animation: loadingDots 1.4s infinite ease-in-out both;
}

.loading-dots span:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dots span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loadingDots {
  0%, 80%, 100% { 
    transform: scale(0);
    opacity: 0.6;
  }
  40% { 
    transform: scale(1);
    opacity: 1;
  }
}

/* 添加打字机光标效果 */
.typing-cursor {
  display: inline-block;
  width: 2px;
  height: 16px;
  background-color: #333;
  margin-left: 2px;
  vertical-align: middle;
  animation: blink 0.7s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}
</style>
